<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="mini" class="btn-add" @click="openDialog(0)">添加权限</el-button>
      <!-- 表格 -->
      <el-table :data="list" row-key="id" default-expand-all>
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button v-if="row.type === 1" type="text" size="mini" @click="openDialog(row.id)">添加</el-button>
            <el-button type="text" size="mini" @click="openDialog(row)">编辑</el-button>
            <el-popconfirm
              title="确认删除该权限吗？"
              @onConfirm="delPermission(row.id)"
            >
              <el-button slot="reference" type="text" size="mini" style="margin-left: 10px">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      width="50%"
      @close="close"
    >
      <el-form ref="formRef" :model="params" :rules="rules" label-width="120px" style="width: 650px">
        <el-form-item prop="name" label="权限名称">
          <el-input v-model="params.name" />
        </el-form-item>
        <el-form-item prop="code" label="权限标识">
          <el-input v-model="params.code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="params.description" />
        </el-form-item>
        <el-form-item label="开启">
          <el-switch v-model="params.enVisible" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { perAddPermissionApi, perDeletePermissionAPi, perGetPermissionListApi, perUpdatePermissionApi } from '@/api/permission'
import { forEachTreeList, transListToTreeData } from '@/utils'

export default {
  name: 'Permission',
  data() {
    return {
      defaultList: [], // 权限点列表 => 未转成树形结构
      list: [], // 权限点列表 => 已转成树形结构
      title: '',
      dialogVisible: false,
      defaultParams: {
        name: '',
        code: '',
        description: '',
        type: null,
        pid: null,
        enVisible: '0'
      },
      params: {
        name: '',
        code: '',
        description: '',
        type: null,
        pid: null,
        enVisible: '0'
      },
      oldName: '',
      oldCode: '',
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.params.id) {
                // 编辑
                let filterArr = []
                filterArr = this.defaultList.filter(item => item.name !== this.oldName)
                filterArr.some(item => item.name === value) ? callback(new Error(`已存在${value}权限名称!`)) : callback()
              } else {
                // 新增
                forEachTreeList(this.list, 'name', value) ? callback(new Error(`已存在${value}权限名称!`)) : callback()
              }
            }, trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.params.id) {
                // 编辑
                let filterArr = []
                filterArr = this.defaultList.filter(item => item.code !== this.oldCode)
                filterArr.some(item => item.code === value) ? callback(new Error(`已存在${value}权限标识!`)) : callback()
              } else {
                // 新增
                forEachTreeList(this.list, 'code', value) ? callback(new Error(`已存在${value}权限标识!`)) : callback()
              }
            }, trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    /**
     * 获取权限点列表
     */
    async getPermissionList() {
      this.defaultList = await perGetPermissionListApi()
      this.list = transListToTreeData(this.defaultList, 0)
    },
    /**
     * 打开弹层
     * @param params
     */
    openDialog(params) {
      if (typeof params === 'number') {
        this.title = '新增权限点'
        this.params.pid = params
        params === 0 ? this.params.type = 1 : this.params.type = 2
      } else if (typeof params === 'object') {
        this.title = '编辑权限点'
        this.params = { ...params }
        this.oldName = params.name
        this.oldCode = params.code
      }

      this.dialogVisible = true
    },
    /**
     * 弹窗确认事件
     */
    async onSubmit() {
      await this.$refs.formRef.validate()

      if (this.params.id) {
        await perUpdatePermissionApi(this.params)
        this.$message.success('编辑权限点成功~')
      } else {
        await perAddPermissionApi(this.params)
        this.$message.success('新增权限点成功~')
      }

      this.close()
      this.getPermissionList()
    },
    /**
     * 关闭弹层
     */
    close() {
      this.dialogVisible = false
      this.params = { ...this.defaultParams }
      this.$refs.formRef.resetFields()
    },
    async delPermission(id) {
      await perDeletePermissionAPi(id)
      this.$message.success('删除权限点成功~')
      this.getPermissionList()
    }
  }
}
</script>

<style scoped>
.btn-add {
  margin: 10px;
}
</style>
